<?php

namespace app\store\service;

use app\store\model\SpikeMeeting;
use think\facade\Db;

class SpikeMeetingService
{

    public function getSpikeMeetingList($time)
    {   
        $store_id = session('store_id');

        $model = new SpikeMeeting();
        $query = $model->withOutField('desc')
                       ->withCount('session')
                       ->where('store_id',$store_id);

        if (!empty($time)){
            $query->where('activity_time',$time);
        }


        $spikeMeetings = $query ->paginate(10);
        
        return  $spikeMeetings;
        
    }

    public function findSpikeMeeting($id)
    {
        $model = new SpikeMeeting();
        $spikeMeeting = $model->withOutField('create_time,update_time,delete_time')->with('session')->find($id);
        if(empty($spikeMeeting)){
            return [];
        }

        $arr = $spikeMeeting->toArray();
        
        $column = array_column($arr['session'],'session_title');
        $arr['session'] = json_encode($column);
        
        return $arr;
        
    }


    public function saveSpikeMeeting($data)
    {
        $data['store_id'] = session('store_id');

       
        $model = SpikeMeeting::create($data);

        $sessions = [];

        foreach($data['session_title'] as $k => $v){
            $sessions[$k]['session_title'] = $v;
            $time = strtotime($data['activity_time'] . " $v");
            $sessions[$k]['start_time'] = $time;
            $sessions[$k]['end_time'] = $time+3600;
        }

        $model->session()->saveAll($sessions);

        return $model;
    }


    public function updateSpikeMeeting($data)
    {
        if (!empty($data['session_values'])){
            $arr =  json_decode($data['session_values'],true);
            Db::name('spike_session')->whereIn('session_title',$arr)->delete();
        }

        $model = SpikeMeeting::update($data);

        $sessions = [];
        foreach($data['session_title'] as $k => $v){
            $sessions[$k]['session_title'] = $v;
            $time = strtotime($data['activity_time'] . " $v");
            $sessions[$k]['start_time'] = $time;
            $sessions[$k]['end_time'] = $time+3600;
        }

        $model->session()->saveAll($sessions);

        return $model;
    }

    
}